import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_menu/app_config.dart';
import 'package:flutter_menu/biz/order/order_pg.dart';
import 'package:flutter_menu/data/base_provider.dart';
import 'package:flutter_menu/data/provider/formula_provider.dart';
import 'package:flutter_menu/data/provider/option_material_provider.dart';
import 'package:flutter_menu/model/category_model.dart';
import 'package:flutter_menu/model/formula_model.dart';
import 'package:flutter_menu/model/material_model.dart';
import 'package:flutter_menu/model/menu_model.dart';
import 'package:flutter_menu/model/product_model.dart';
import 'package:flutter_menu/model/shope_model.dart';
import 'package:flutter_menu/objectbox.g.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

class ShopProvider extends BaseProvider<ShopModel> {
  ShopProvider(super.store);

  ShopModel? getShopInfo() {
    return box.getAll().firstOrNull;
  }

  bool? _enableMaterialLinkProduct;

  bool isEnableMaterialLinkProduct() {
    _enableMaterialLinkProduct ??=
        (getShopInfo()?.enableMaterialLinkProduct == true);
    return _enableMaterialLinkProduct ?? false;
  }

  List<MarketTypeModel>? _marketTypeList;

  List<MarketTypeModel>? getMargetTypeList() {
    _marketTypeList ??= (getShopInfo()?.marketTypeList);
    return _marketTypeList;
  }

  MarketTypeModel? getMarketTypeByType(int? code) {
    var margetTypeList = getMargetTypeList();
    return margetTypeList?.firstWhereOrNull((item) {
      return item.code == code;
    });
  }

  bool isTimeInRange(String? beginTime, String? endTime) {
    if (beginTime == null || endTime == null) return true;
    // 将时间字符串转换为 DateTime 对象
    final now = DateTime.now();
    final currentTime = DateFormat.Hm().format(now); // 获取当前时间，格式为 "HH:mm"
    final current = DateFormat.Hm().tryParse(currentTime);
    final begin = DateFormat.Hm().tryParse(beginTime);
    final end = DateFormat.Hm().tryParse(endTime);
    if (begin == null || end == null || current == null) return true;
    // 检查当前时是否在开始时间和结束时间之间
    return current.isAfter(begin) && current.isBefore(end);
  }

  bool checkSupplyTimeIsValid(List<SupplyTime> supplyTimeList) {
    debugPrint("checkSupplyTimeIsValid: $supplyTimeList");
    final now = DateTime.now();
    final currentDay = now.weekday; // 获取当前星期几
    var filteredSupplyTime = supplyTimeList.where((timeItem) {
      // 检查当前日期是否在 supplyTime 的 days 中
      if (timeItem.days?.contains(currentDay) ?? false) {
        // 查找对应的市场类型配置
        final config =
            getMarketTypeByType(int.tryParse(timeItem.marketTypeCode ?? ""));

        // 检查当前时间是否在 beginTime 和 endTime 之间
        return isTimeInRange(config?.beginTime, config?.endTime);
      }
      return false;
    }).toList();
    return filteredSupplyTime.isNotEmpty;
  }
}
